package com.ray.web.controller;


import com.ray.common.utils.Result;
import com.ray.common.utils.WebUtils;
import com.ray.web.entity.Loginfo;
import com.ray.web.entity.User;
import com.ray.web.service.LoginfoService;
import com.ray.web.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author ray
 * @since 2020-12-02
 */
@Controller
@RequestMapping("/sys/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private LoginfoService loginfoService;

    /**
     * 登录
     * form表单提交不能用restful
     *
     */
    @PostMapping("login")
    public String login(String username, String password, Model model){
        //subject与shiro进行交互
        Subject subject = SecurityUtils.getSubject();
        //token封装用户信息
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        //shiro开始登录验证
        try {
            subject.login(token);
            User user = (User)subject.getPrincipal();
            //将user存入session
            subject.getSession().setAttribute("user", user);
            //记录登录日志
            Loginfo loginfo = new Loginfo();
            loginfo.setLoginName(user.getUsername());
            loginfo.setLoginIp(WebUtils.getRemoteHost());
            loginfo.setLoginTime(new Date());
            loginfoService.save(loginfo);

            return "redirect:/";
        } catch (UnknownAccountException e) {
            model.addAttribute("msg","用户不存在");
            return "/view/login";
        }catch (IncorrectCredentialsException e){
            model.addAttribute("msg","密码不正确");
            return "/view/login";
        }
    }


    /**
     * 权限不足
     *
     */
    @GetMapping("/unauth")
    @ResponseBody
    public String unauth(){
        return "权限不足";
    }

    /**
     * logout
     *
     */
    @GetMapping("/logout")
    public String logout(){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "/view/login";
    }

    @GetMapping("/userList")
    @ResponseBody
    public Map<String, Object> userList(){
        List<User> userList = userService.list();
        Map<String, Object> tableData = new HashMap<String, Object>();
        //这是layui要求返回的json数据格式
        tableData.put("code", 0);
        tableData.put("msg", "");
        tableData.put("count", userList.size());
        tableData.put("data", userList);
        return tableData;
    }




}
